<template>
  <div class="app-container">
    <div class="container ">
      <el-row :gutter="20" class="filter-container">
        <el-col
          v-if="isManage"
          :span="20"
        >
          <el-button type="primary" size="mini" @click="submitForm('open')">
            <i class="el-icon-circle-plus-outline" />&nbsp;添加用户</el-button>
          <el-button v-if="isAdmin1" type="primary" size="mini" @click="dialogTableVisible = true">
            <i class="el-icon-setting" />&nbsp;部门管理</el-button>
        </el-col>
        <el-col v-if="isManage" :span="4" style="text-align: right;">
<!--          v-if="isAdmin1"-->
          <el-select
            v-if="isAdmin1"
            v-model="listQuery.departId"
            placeholder="全部部门"
            size="mini"
            clearable
            @change="queryDepartC"
          >
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-col>
        <el-col v-if="!isManage" :span="4" style="text-align: right;" :offset="20">
          <el-select
            v-model="listQuery.departId"
            placeholder="全部部门"
            size="mini"
            clearable
            @change="queryDepartC"
          >
            <el-option
              v-for="item in options"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-col>
      </el-row>
      <!-- 添加用户弹框 -->
      <el-dialog
        :title="titleStatus"
        :visible.sync="addUserdialogV"
        width="30%"
        :before-close="handleClose"
        center
      >
        <el-form
          ref="ruleForm"
          :rules="rules"
          label-width="100px"
          size="mini"
          :model="formAddUser"
        >
          <el-form-item label="账号:" prop="userName">
            <el-input
              v-model="formAddUser.userName"
              autofocus
              :disabled="isUserEdit || isUserEdit == null || editPassword"
            />
          </el-form-item>
          <el-form-item v-if="titleStatus != '权限管理'" label="手机号:">
            <el-input v-model="formAddUser.phone" :maxlength="11" :disabled="isUserEdit == null || editPassword" />
          </el-form-item>
          <el-form-item v-if="isUserEdit && !editPassword" label="用户头像:" prop="logUrl">
            <el-upload
              class="avatar-uploader"
              action="http://10.10.10.11:9006/file/upload"
              :show-file-list="false"
              :headers="upHeaders"
              accept=".jpg,.jpeg,.png,.JPG,.JPEG,.PNG"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar">
              <i v-else class="el-icon-plus avatar-uploader-icon" />
            </el-upload>
          </el-form-item>
          <!--          <el-form-item v-if="isUserEdit && !editPassword" label="昵称:" prop="nickName">-->
          <!--            <el-input v-model="formAddUser.nickName" />-->
          <!--          </el-form-item>-->
          <el-form-item v-if="!editPassword" label="姓名:" prop="realName">
            <el-input
              v-model="formAddUser.realName"
              :disabled="isUserEdit == null || editPassword"
            />
          </el-form-item>
          <el-form-item v-if="(!isUserEdit && isUserEdit !=null) || editPassword" label="密码:" prop="password">
            <el-input v-model="formAddUser.password" type="password" />
          </el-form-item>
          <el-form-item v-if="(!isUserEdit && isUserEdit !=null) || editPassword" label="确认密码:" prop="comfirmPassword">
            <el-input v-model="formAddUser.comfirmPassword" type="password" />
          </el-form-item>
          <el-form-item v-if="(isUserEdit && isUserEdit !=null && !editPassword) && formAddUser.roleType != 1024" label="管理员:" prop="addId">
            <el-select
              v-model="formAddUser.addId"
              placeholder="请选择"
              style="width:160px"
            >
              <el-option
                v-for="item in options2"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="((!editPassword && isUserEdit) || (!editPassword && !isUserEdit && isUserEdit !=null))
              && formAddUser.roleType != 1024"
            label="部门:"
            prop="departmentId"
          >
            <el-select
              v-model="formAddUser.departmentId"
              placeholder="请选择"
              :disabled="options.length > 1 ? false : true"
              style="width:160px"
            >
              <el-option
                v-for="item in options"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            v-if="!isUserEdit && !editPassword"
            v-model="formAddUser.roleType"
            label="角色类型:"
            prop="roleType"
          >
            <!-- <el-radio v-model="formAddUser.roleType" :label="1024">超级管理员</el-radio> -->
            <el-radio v-model="formAddUser.roleType" :label="1025">管理员</el-radio>
            <el-radio v-if="isAdmin1" v-model="formAddUser.roleType" :label="1026">审计员</el-radio>
            <el-radio v-model="formAddUser.roleType" :label="1027">普通用户</el-radio>
            <!-- <el-radio v-model="formAddUser.roleType" :label="1028">安全管理员</el-radio> -->
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" size="mini" @click="submitForm('ruleForm',editPassword)">确 定</el-button>
          <el-button size="mini" @click="handleClose">取 消</el-button>
        </span>
      </el-dialog>
      <!-- 删除用户弹框 -->
      <el-dialog
        title="删除用户"
        :visible.sync="delUserdialogV"
        width="25%"
        :before-close="handleClose"
        center
      >
        <div class="text-algin-center">
          <el-avatar :size="60" src="../../assets/icons_slices/img_opo_tip.png">
            <img src="../../assets/icons_slices/img_opo_tip.png">
          </el-avatar>
          <h3>确定删除{{ userCache.userName }}用户吗？</h3>
          <span>删除后不可恢复</span>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button type="danger" size="mini" @click="handleDelete('comfirmDelUser')">删除</el-button>
          <el-button size="mini" @click="delUserdialogV = false">取 消</el-button>
        </span>
      </el-dialog>
      <el-table
        v-loading="listLoading"
        element-loading-text="正在加载中..."
        element-loading-background="rgba(0, 0, 0, 0.5)"
        :data="list"
        border
        fit
        highlight-current-row
      >
        <el-table-column label="账号" align="center" width="120">
          <template slot-scope="scope">
            {{ scope.row.userName }}
          </template>
        </el-table-column>
        <el-table-column
          label="账号类型"
          width="100"
          align="center"
        >
          <template slot-scope="scope">
            <div v-if="scope.row.roleType == 1027">
              普通用户
            </div>
            <div v-else style="color: red;">
              {{ scope.row.roleType=== 1024?'超级管理员':
                scope.row.roleType=== 1025?'管理员':
                scope.row.roleType=== 1026?'审计员': '普通用户' }}
            </div>
          </template>
        </el-table-column>
        <el-table-column label="姓名" width="120" align="center">
          <template slot-scope="scope">
            {{ scope.row.realName }}
          </template>
        </el-table-column><el-table-column label="手机号" width="120" align="center">
          <template slot-scope="scope">
            {{ scope.row.phone }}
          </template>
        </el-table-column>
        <el-table-column label="所属部门" width="230" align="center">
          <template slot-scope="scope">
            {{ scope.row.departmentName }}
          </template>
        </el-table-column>
        <el-table-column label="管理员" width="130" align="center">
          <template slot-scope="scope">
            {{ scope.row.addName }}
          </template>
        </el-table-column>
        <!-- <el-table-column label="更新时间" width="200" align="center">
          <template slot-scope="scope">
            {{ scope.row.updateTime }}
          </template>
        </el-table-column> -->
        <el-table-column :width="420" fixed="right" style="text-align: center;" align="center">
          <template slot="header" style="text-align: center;">
            <span>操作</span>
          </template>
          <template slot-scope="scope">
            <el-button
              style="width: 80px"
              v-if="isManage && scope.row.roleType != 1024"
              size="mini"
              @click="handleEdit('permission', scope.row)"
            >权限管理</el-button>
            <el-button
              style="width: 80px"
              type="primary"
              size="mini"
              @click="handleEdit('edit', scope.row)"
            ><i class="el-icon-edit" />编辑</el-button>
            <el-button
              style="width: 80px"
              type="primary"
              size="mini"
              @click="handleEdit('editPassword', scope.row)"
            >修改密码</el-button>
            <el-button
              style="width: 80px"
              v-if="isManage && scope.row.roleType !== 1024"
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
    </div>
    <el-dialog title="部门管理" :visible.sync="dialogTableVisible" width="60%" height="80%">
      <el-button
        type="primary"
        size="mini"
        style="margin-bottom: 10px"
        @click="addNewType('add')"
      >新增部门</el-button>
      <el-table
        :data="options1"
        height="800px"
        style="width: 100%;
         max-height: 360px;
        overflow-y: scroll;"
      >
        <el-table-column
          label="部门名称"
          width=""
          align="center"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="部门管理员"
          align="center"
        >
          <template slot-scope="scope">
            <span>{{ scope.row.manageName? scope.row.manageName : '无' }}</span>
          </template>
        </el-table-column>
        <!-- <el-table-column label="修改时间"> -->
        <!--          <template slot-scope="scope">-->
        <!--            <span>{{ scope.row.updateTime }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <!--        <el-table-column label="说明">-->
        <!--          <template slot-scope="scope">-->
        <!--            <span>{{ scope.row.descr }}</span>-->
        <!--          </template>-->
        <!--        </el-table-column>-->
        <el-table-column
          label="操作"
          width="220"
          align="center"
        >
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              @click="addNewType('edit',scope.row)"
            >编辑</el-button>
            <el-button
              v-if="isAdmin1"
              type="danger"
              size="mini"
              @click="addNewType('del',scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
    <el-dialog
      title="部门管理"
      :visible.sync="addTypedialogV"
      width="25%"
      center
    >
      <el-form
        label-width="100px"
        size="mini"
      >
        <el-form-item label="部门名称:">
          <el-input v-model="typeName" :maxlength="15" :minlength="2" />
        </el-form-item>
        <el-form-item label="部门管理员:">
          <el-select v-model="manageId" placeholder="请选择">
            <el-option
              v-for="item in optionsDpart"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="addNewType">确 定</el-button>
        <el-button size="mini" @click="addTypedialogV = false">取 消</el-button>
      </span></el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { softList, softAdd, softDel, softPut, softTypeList, softTypeAdd, softTypePut, softTypeDel,
  softSecretDel, softSecretPage } from '@/api/softManage'
import { userList, userAdd
  , userDel, userPut, userPermission, userPasswordPut, getListManage, sysDepartmentList } from '@/api/user'
import { departmentDel, departmentAdd, departmentPut, departmentList, departmentPage } from '@/api/department'
import { getToken } from '@/utils/auth'
import { getCookie, setCookie, removeCookie } from '@/utils/cookie'
import Pagination from '@/components/Pagination'
import { title } from '../../settings'
import { Alert } from 'element-ui'
export default {
  computed: {
    ...mapGetters([
      'name',
      'sidebar',
      'avatar',
      'userInfo'
    ]),
    isManage() {
      // console.log(getCookie('userInfo').realName)
      if (getCookie('userInfo')) {
        return JSON.parse(getCookie('userInfo')).roleType === 1024 ||
        JSON.parse(getCookie('userInfo')).roleType === 1025
      } else {
        return this.userInfo.roleType === 1024
      }
    }
  },
  components: { Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'gray',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    var validatePass2 = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请再次输入密码'))
      } else if (value !== this.formAddUser.password) {
        callback(new Error('两次输入密码不一致!'))
      } else {
        callback()
      }
    }
    return {
      isAdmin1: false,
      manageId: '',
      addTypedialogV: false,
      editPassword: false,
      upHeaders: {
        ACCESS_TOKEN: getToken()
      },
      imageUrl: '',
      value: '1',
      options1: [
        // {
        //   name: '调度中心'
        // }, {
        //   name: '市场部'
        // }
      ],
      optionsDpart: [
        // {
        //   name: '调度中心'
        // }, {
        //   name: '市场部'
        // }
      ],
      options2: [
        {
          id: 1,
          name: '周烈'
        }, {
          id: 2,
          name: '周烈1'
        }
      ],
      dialogTableVisible: false,
      options: [],
      rules: {
        departmentId: [
          { required: true, message: '请选择部门', trigger: 'change' }
        ],
        addId: [
          { required: true, message: '请选择管理员', trigger: 'change' }
        ],
        roleType: [
          { required: true, message: '请选择', trigger: 'change' }
        ],
        userName: [
          { required: true, message: '请输入账号', trigger: 'change' },
          { min: 2, max: 16, message: '长度在 2 到 16个字符', trigger: 'change' }
        ],
        realName: [
          { required: true, message: '所有人', trigger: 'change' },
          { min: 2, max: 16, message: '长度在 2 到 16个字符', trigger: 'change' }
        ],
        phone: [
          { required: true, message: '请输入手机号', trigger: 'change' },
          { min: 11, max: 11, message: '手机号长度不对', trigger: 'change' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'change' },
          { min: 6, max: 25, message: '长度在 6 到 25 个字符', trigger: 'change' }
        ],
        comfirmPassword: [
          { required: true, validator: validatePass2, trigger: 'change' }
          // { required: true, message: '请输入确认密码', trigger: 'change' },
          // { min: 6, max: 25, message: '长度在 6 到 25 个字符', trigger: 'change' }
        ]
      },
      userCache: {
        addName: '1',
        id: '',
        phone: '',
        roleType: '1',
        userName: '',
        password: '',
        comfirmPassword: '',
        departmentId: '',
        header: '',
        nickName: '',
        realName: '',
        remark: '',
        sortNum: 0
      },
      formAddUser: {
        addId: '0',
        addName: '1',
        id: '',
        phone: '',
        departmentId: '',
        roleType: 1027,
        userName: '',
        password: '',
        comfirmPassword: '',
        header: '',
        nickName: '',
        realName: '',
        remark: '',
        sortNum: 0
      },
      delUserdialogV: false,
      addUserdialogV: false,
      total: 10,
      list: null,
      listLoading: true,
      listQuery: {
        departId: '',
        page: 1,
        limit: 10
      },
      typeName: '',
      isUserEdit: false,
      titleStatus: '添加用户',
      typeCache: {}
    }
  },
  created() {
    if (JSON.parse(getCookie('userInfo')).roleType === 1024) {
      this.isAdmin1 = true
    } else {
      this.isAdmin1 = false
    }
    // console.log(this.userInfo)
    this.getDepartmentList()
    // this.getSysDepartmentList()
    this.getTypeList()
    this.fetchData()
  },
  methods: {
    getListManage() {
      getListManage().then(res => {
        if (res.code == 200) {
          this.options2 = res.data.data
        }
      })
    },
    addNewType(params, params1) {
      this.getSysDepartmentList()
      if (params === 'add') {
        this.typeName = ''
        this.manageId = ''
        this.addTypedialogV = true
        this.typeCache.id = ''
      } else if (params === 'del') {
        this.$confirm('确定删除吗？', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          departmentDel({
            ids: params1.id
          }).then(res => {
            if (res.code === 200) {
              this.$message.success('删除成功')
              this.getTypeList()
            }
          })
        }).catch(() => {
          this.$message.info('已点击取消')
        })
      } else if (params === 'edit') {
        this.typeCache = params1
        this.typeName = params1.name
        this.manageId = params1.manageId
        this.addTypedialogV = true
      } else {
        if (this.typeName.length > 2) {
          // console.log(this.typeCache)
          if (this.typeCache.id) {
            departmentPut({
              id: this.typeCache.id,
              name: this.typeName,
              manageId: this.manageId,
              remark: this.typeDec,
              sortNum: 0
            }).then(res => {
              if (res.code === 200) {
                this.$message.success('修改成功')
                this.addTypedialogV = false
                this.getTypeList()
              }
            }).catch(() => {
              this.isUserEdit = true
            })
          } else {
            departmentAdd({
              name: this.typeName,
              manageId: this.manageId,
              sortNum: 0
            }).then(res => {
              if (res.code === 200) {
                this.$message.success('添加成功')
                this.addTypedialogV = false
                this.getTypeList()
              }
            })
          }
        } else {
          this.$message.warning('请输入2-15个字符的部门名称!')
        }
      }
    },
    getTypeList() {
      departmentPage({
        limit: 50,
        page: 1
      }).then(res => {
        if (res.code === 200) {
          this.options1 = []
          res.data.data.map(item => {
            if (item.id !== '1025' || item.id !== '55904214559285248') {
              this.options1.push(item)
            }
          })
        }
      })
    },
    getSysDepartmentList() {
      sysDepartmentList({
        limit: 50,
        page: 1
      }).then(res => {
        if (res.code === 200) {
          this.optionsDpart = res.data.data
        }
      })
    },
    getDepartmentList() {
      departmentList({
        limit: 50,
        page: 1
      }).then(res => {
        if (res.code === 200) {
          this.options = []
          res.data.data.map(item => {
            if (item.id !== '1025' && item.id !== '55904214559285248') {
              this.options.push(item)
            }
          })
        }
      })
    },
    queryDepartC() {
      this.getList()
    },
    initData() {
      if (this.$refs.ruleForm) {
        this.$refs.ruleForm.clearValidate()
      }
      this.formAddUser = {
        id: '',
        phone: '',
        departmentId: '',
        roleType: 1027,
        userName: '',
        password: '',
        comfirmPassword: '',
        header: '',
        nickName: '',
        realName: '',
        remark: '',
        sortNum: 0
      }
      if (this.options.length > 0) {
        this.formAddUser.departmentId = this.options[0].id
      }
    },
    handleClose(params) {
      this.addUserdialogV = false
      this.delUserdialogV = false
      this.initData()
      this.getList()
    },
    handleAvatarSuccess(res, file) {
      if (res && res.code === 200) {
        this.formAddUser.header = res.data + ''
      } else {
        this.$message.warning('请求异常')
      }
      this.imageUrl = URL.createObjectURL(file.raw)
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG|png格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    submitForm(formName, editPassword) {
      this.addUserdialogV = true
      if (formName === 'open') {
        this.getDepartmentList()
        this.isUserEdit = false
        this.editPassword = false
        this.titleStatus = '添加用户'
        this.initData()
      } else {
        if (editPassword) {
          this.$refs['ruleForm'].validate((valid) => {
            if (valid) {
              userPasswordPut({
                id: this.userInfo.roleType === 1 ? this.userCache.id : null,
                password: this.formAddUser.password
              }).then(res => {
                if (res.code === 200) {
                  this.imageUrl = ''
                  this.addUserdialogV = false
                  // this.$refs[formName].resetFields()
                  this.initData()
                  this.getList()
                }
              })
            }
          })
        } else if (this.isUserEdit) {
          this.$refs[formName].validate((valid) => {
            if (valid) {
              userPut({
                addId: this.formAddUser.addId,
                id: this.formAddUser.id,
                header: this.formAddUser.header,
                nickName: this.formAddUser.nickName,
                realName: this.formAddUser.realName,
                remark: this.formAddUser.remark,
                phone: this.formAddUser.phone,
                departmentId: this.formAddUser.departmentId
              }).then(res => {
                if (res.code === 200) {
                  this.imageUrl = ''
                  this.addUserdialogV = false
                  // this.$refs[formName].resetFields()
                  this.initData()
                  this.getList()
                }
              })
            }
          })
        } else if (this.isUserEdit == null) {
          userPermission({
            roleType: this.formAddUser.roleType,
	          userId: this.formAddUser.id
          }).then(res => {
            if (res.code === 200) {
              this.addUserdialogV = false
              this.initData()
              // this.$refs[formName].resetFields()
              this.getList()
            }
          })
        } else {
          this.$refs[formName].validate((valid) => {
            if (valid) {
              userAdd(this.formAddUser).then(res => {
                if (res.code === 200) {
                  this.addUserdialogV = false
                  this.getList()
                  this.initData()
                  // this.$refs[formName].resetFields()
                }
              })
              // alert('submit!')
            } else {
              return false
            }
          })
        }
      }
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    handleEdit(type, row) {
      if (type === 'editPassword') {
        this.initData()
        this.titleStatus = '修改密码'
        this.editPassword = true
      } else if (type === 'permission') {
        this.initData()
        this.titleStatus = '权限管理'
        this.editPassword = false
        this.isUserEdit = null
      } else if (type === 'edit') {
        this.initData()
        this.getListManage()
        this.titleStatus = '完善用户信息'
        this.editPassword = false
        this.isUserEdit = true
      }
      this.addUserdialogV = true
      this.formAddUser = row
      this.imageUrl = row.header
      this.userCache = row
    },
    handleDelete(index, row) {
      if (index === 'comfirmDelUser') {
        userDel({ ids: this.userCache.id }).then(res => {
          if (res.code === 200) {
            this.userCache = {}
            this.getList()
            this.delUserdialogV = false
          }
        })
        this.delUserdialogV = false
      } else {
        this.userCache = row
        this.delUserdialogV = true
      }
    },
    getList() {
      this.listLoading = true
      userList(this.listQuery).then(response => {
        // console.log(response)
        this.list = response.data.data
        this.total = response.totalCount
        this.listLoading = false
      })
    },
    fetchData() {
      this.getList()
    }
  }
}
</script>
<style scoped>
  /deep/.el-table th>.cell {
    text-align: center;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 88px;
    height: 88px;
    line-height: 88px;
    text-align: center;
  }
  .avatar {
    width: 88px;
    height: 88px;
    display: block;
  }
  .text-algin-center {
    text-align: center;
  }
  .filter-container{
    margin: 20px;
  }
</style>
